package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import common.Constant;

import util.ImageThubHQ;
import util.KeyGen;
import util.MyJson;

/**
 * Servlet implementation class UploadImg
 */
public class UploadImg extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImg() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		
		String key = "";
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			if ( "user".equals(cookies[i].getName()))
				key = cookies[i].getValue();
		}

		if (!KeyGen.cookieValid(key)) {
			pw.write(MyJson.toJson("msg", "您尚未登录，请登录后再继续操作，谢谢！"));
		} 
		else{
			
			DiskFileItemFactory dfif=new DiskFileItemFactory();
			dfif.setSizeThreshold(5*1024*1024);
			ServletFileUpload servletfileupload=new ServletFileUpload(dfif);
			servletfileupload.setSizeMax(10*1024*1024);
			try{
				List<FileItem> files=servletfileupload.parseRequest(request);
				for(FileItem f:files){
					if(f.isFormField()){//如果该项是表单项，不是文件上传项
						continue;
					}
					else{
						String basename =String.valueOf((new Date()).getTime()+new Random().nextInt(10000));
						String fname = Constant.imgpath + basename + "_source.jpg";
						String imgname=basename + "_0.jpg";
						
						f.write(new File(fname));
						
						ImageThubHQ hq = new ImageThubHQ();
						hq.getThub(fname, Constant.imgpath + imgname, 256,1.0f);
						pw.write(MyJson.toJson("succ",Constant.imgurl+Constant.imgfilter+imgname));
//						pw.write(MyJson.toJson("succ","http://ww2.sinaimg.cn/bmiddle/5d738637gw1dr8y0sf4bgj.jpg"));
					}
				}
			}catch(Exception e){
				e.printStackTrace();
				pw.write(MyJson.toJson("msg", "系统异常，请稍后再试，谢谢！"));
			}
			/*
			ServletInputStream sit=request.getInputStream();
			
			
			
			System.out.println("inputstream length:"+sit.available()+"   "+request.getContentLength());
			if (sit.available()>=0 && sit.available()<1024*1024*5){
			BufferedImage bimg = ImageIO.read(sit);
			if (null!=bimg){
			String basename =String.valueOf((new Date()).getTime());
			String fname = Constant.imgpath + basename + "_source.jpg";
			String imgname=basename + "_0.jpg";
			File file = new File(fname);
			
			ImageIO.write(bimg, "JPEG", file);
			sit.close();

			ImageThubHQ hq = new ImageThubHQ();
			hq.getThub(fname, Constant.imgpath + imgname, 256,1.0f);
			Cookie cookie=new Cookie("imgpath", key);
			cookie.setMaxAge(Constant.CookieExpired);
			cookie.setPath("/");
			response.addCookie(cookie);			
			pw.write(MyJson.toJson("msg","0"));
			}
			}
			else{
				pw.write(MyJson.toJson("msg","抱歉，上传图片的大小不能超过5M，谢谢！"));
			}
			*/
		}
		pw.flush();
		pw.close();
	}

}
